package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.FoodDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Food;
import com.itheima.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = FoodService.class)
@Transactional
public class FoodServiceImpl implements FoodService {
    @Autowired
    private FoodDao foodDao;

    @Override
    public void add(ArrayList<Food> list) {
        if (list != null && list.size() > 0) {
            for (Food food : list) {
                int count = foodDao.findCountByCode(food.getCode());
                if (count > 0) {
                    foodDao.edit(food);
                } else {
                    foodDao.add(food);
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手插件
        PageHelper.startPage(currentPage, pageSize);
        Page<Food> page = foodDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Food> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public void save(Food food) {
        foodDao.add(food);
    }

    @Override
    public void delete(Integer id) {
        foodDao.delete(id);
    }

    @Override
    public void edit(Food food) {
        foodDao.update(food);
    }

    @Override
    public Food findById(Integer id) {
        return foodDao.findById(id);
    }
}
